$(function() {

    if ($("#taskId").attr("paramVal")) {
	    $("#taskId").find("option[value='" + $("#taskId").attr("paramVal") + "']").attr("selected",true);
	    $('#taskId').val($("#taskId").attr("paramVal"));
	}

	// filter Time
    var rangesConf = {};
    rangesConf["最近一小时"] = [moment().subtract(1, 'hours'), moment()];
    rangesConf["今日"] = [moment().startOf('day'), moment().endOf('day')];
    rangesConf["昨日"] = [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')];
    rangesConf["本月"] = [moment().startOf('month'), moment().endOf('month')];
    rangesConf["上个月"] = [moment().subtract(1, 'months').startOf('month'), moment().subtract(1, 'months').endOf('month')];
    rangesConf["最近一周"] = [moment().subtract(1, 'weeks').startOf('day'), moment().endOf('day')];
    rangesConf["最近一月"] = [moment().subtract(1, 'months').startOf('day'), moment().endOf('day')];

    $('#filterTime').daterangepicker({
        autoApply:false,
        singleDatePicker:false,
        showDropdowns:false,        // 是否显示年月选择条件
        timePicker: true, 			// 是否显示小时和分钟选择条件
        timePickerIncrement: 10, 	// 时间的增量，单位为分钟
        timePicker24Hour : true,
        opens : 'left', //日期选择框的弹出位置
        ranges: rangesConf,
        locale : {
            format: 'YYYY-MM-DD HH:mm:ss',
            separator : ' - ',
            customRangeLabel : "自定义" ,
            applyLabel : "确定" ,
            cancelLabel : "取消" ,
            fromLabel : "起始时间" ,
            toLabel : "结束时间" ,
            daysOfWeek : "日,一,二,三,四,五,六".split(',') ,        // '日', '一', '二', '三', '四', '五', '六'
            monthNames : "一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月,十二月".split(',') ,        // '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'
            firstDay : 1
        },
        startDate: rangesConf["今日"][0],
        endDate: rangesConf["今日"][1]
    });

	// init date tables
	var dataTable = $("#data_list").dataTable({
		"deferRender": true,
		"processing" : true, 
	    "serverSide": true,
		"ajax": {
			url: base_url + "/joblog/pageList",
	        data : function ( d ) {
				var obj = {};
				obj.start = d.start;
				obj.length = d.length;
				obj.taskId = $('#taskId').val();
				obj.status = $('#status').val();
				obj.filterTime = $('#filterTime').val();
				return obj;
            }
	    },
	    "searching": false,
	    "ordering": false,
	    //"scrollX": true,	// X轴滚动条，取消自适应
	    "columns": [
	                { data: 'sysId', "visible" : false},
	                { data: 'taskId', "width":'6%'},
	                { data: 'name'},
					{ data: 'createTime', "bSortable" : false, "width":'15%'},
					{ data: 'modifyTime', "bSortable" : false, "width":'15%'},
            		{ data: 'total', "width":'6%'},
            		{ data: 'failCount', "width":'6%'},
            		{ data: 'description', "width":'6%'},
            		{ data: 'msg', "width":'6%',
            		    render : function ( data, type, row ) {
                            if (data) {
                                return '<a href="javascript:;" class="showMsg" _id="'+ row.sysId +'">查看</spam></a>';
                            } else {
                                return '空';
                            }
                        }
            		},
            		{ data: 'path', 'visible': false},
            		{ data: 'status',
            		    "render": function ( data, type, row ) {
                            var html = data;
                            if (data == 200) {
                                html = '<span style="color: green">成功</span>';
                            } else if (data == 500) {
                                html = '<span style="color: red">失败</span>';
                            } else if (data == 0) {
                               html = '';
                            }
                            return html;

                        },
                        "width":'6%'
            		},
	                { data: 'opt' ,
	                	"render": function ( data, type, row ) {
	                		return function(){

	                			// data
                                tableData['key'+row.sysId] = row;

                                // opt
                                var html = '<p id="'+ row.name +'" >'+
                                            '<a href="javascript:;" class="showData" _id="'+ row.sysId +'">查看日志</spam></a>'+
                                            '</p>';
                                return html;
	                		};
	                	},
	                	"width":'10%'
	                }
	            ],
		"language" : {
			"sProcessing" : "处理中...",
			"sLengthMenu" : "每页 _MENU_ 条记录",
			"sZeroRecords" : "没有匹配结果",
			"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页 ) 总记录数 _MAX_ ",
			"sInfoEmpty" : "无记录",
			"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
			"sInfoPostFix" : "",
			"sSearch" : "搜索:",
			"sUrl" : "",
			"sEmptyTable" : "表中数据为空",
			"sLoadingRecords" : "载入中...",
			"sInfoThousands" : ",",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "上页",
				"sNext" : "下页",
				"sLast" : "末页"
			},
			"oAria" : {
				"sSortAscending" : ": 以升序排列此列",
				"sSortDescending" : ": 以降序排列此列"
			}
		}
	});



    // table data
    var tableData = {};

    // msg 弹框
    $("#data_list").on('click', '.showMsg',function() {
        var _id = $(this).attr('_id');
        var row = tableData['key' + _id ];
        ComAlertTec.show(row.msg + "<br/>本次同步条件[" + row.realParams + "]");
    });

	// msg 弹框
    $("#data_list").on('click', '.showData',function() {
        var _id = $(this).attr('_id');
        window.open(base_url + "/joblog/logDetailPage?sysId="+_id);
    });

    // search btn
	$('#searchBtn').on('click', function(){
		dataTable.fnDraw();
	});

});

// Com Alert by Tec theme
var ComAlertTec = {
    html:function(){
        var html =
            '<div class="modal fade" id="ComAlertTec" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content-tec">' +
            '<div class="modal-body"><div class="alert" style="color:#fff;"></div></div>' +
            '<div class="modal-footer">' +
            '<div class="text-center" >' +
            '<button type="button" class="btn btn-info ok" data-dismiss="modal" >确认</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        return html;
    },
    show:function(msg, callback){
        // dom init
        if ($('#ComAlertTec').length == 0){
            $('body').append(ComAlertTec.html());
        }

        // init com alert
        $('#ComAlertTec .alert').html(msg);
        $('#ComAlertTec').modal('show');

        $('#ComAlertTec .ok').click(function(){
            $('#ComAlertTec').modal('hide');
            if(typeof callback == 'function') {
                callback();
            }
        });
    }
};
